module.exports = core;

const path = require("path");
// const fs = require("fs");
const semver = require("semver");
const colors = require("colors/safe");
const userHome = require("user-home");
const pathExits = require("path-exists").sync;
const pkg = require("../package.json");
const log = require("@zreact-cli/log");
// const init = require("@zreact-cli/init");
const exec = require("@zreact-cli/exec");
const constant = require("./const");
const { getNpmSemverVersions } = require("get-npm-info");
const { Command } = require("commander");
const program = new Command();

async function core() {
  //脚手架启动过程
  try {
    await prepare();

    //注册命令
    registerCommand();
  } catch (error) {
    console.log("error:", error.message);
  }
}

function registerCommand() {
  program
    .name(Object.keys(pkg.bin)[0])
    .usage("<command> [options]")
    .version(pkg.version)
    .option("-d, --debug", "是否开启调试模式", false)
    .option("-tp, --targetPath <targetPath>", "是否指定文件调试文件路径", "");

  program
    .command("init [program]")
    .option("-f, --force", "是否强制执行")
    .description("初始化项目")
    .action(exec);

  //监听debug模式
  program.on("option:debug", function () {
    const opts = program.opts(); //获取参数
    if (opts.debug) {
      process.env.LOG_LEVEL = "verbose";
    } else {
      process.env.LOG_LEVEL = "info";
    }
    log.level = process.env.LOG_LEVEL;
  });

  //指定targetPasth
  program.on("option:targetPath", function () {
    //通过环境变量设置属性
    process.env.CLI_TARGETPATH = program._optionValues.targetPath;
  });

  //未知命令监听
  program.on("command:*", function (obj) {
    const availableCommands = program.commands.map((cmd) => cmd.name());
    // console.log(colors.red(`未知的命令: ${obj[0]}`));
    // console.log(colors.red(`可用命令: ${availableCommands.join("、")}`));
  });
  if (program.args && program.args.length < 1) {
    //表示没有命令
    program.outputHelp();
  } else {
    program.parse(process.argv);
  }
}

async function prepare() {
  //查看包的版本号
  checkPkgVersion();

  //检查root账户
  checkRoot();
  //获取用户主目录
  checkUserHome();
  //检查环境变量
  checkEnv();
  //检查是否需要全局更新
  await checkGlobalUpdate();
}

//检查是否需要全局更新
async function checkGlobalUpdate() {
  //1.获取当前版本号和模块名字
  const currentVersion = pkg.version;
  const currentName = pkg.name;
  //2.调用npmAPI 获取版本号(axios, url-join)
  const newVersion = await getNpmSemverVersions(currentVersion, currentName);
  if (newVersion && semver.gt(newVersion, currentVersion)) {
    log.warn(
      colors.yellow(`请手动更新 ${currentName}, 
    当前版本: ${currentVersion}, 
    最新版本:${newVersion},
    更新命令：npm install -g ${currentName}`)
    );
  }
}

//检查环境变量
function checkEnv() {
  //dotenv 包，从.env文件中加载环境变量
  const dotEnv = require("dotenv");
  const dotenvPath = path.resolve(userHome, ".zrc");
  if (pathExits(dotenvPath)) {
    dotEnv.config({
      path: path.resolve(userHome, ".zrc"),
    });
  }
  createDefaultConfig();
}

//创建默认配置
function createDefaultConfig() {
  const cliConfig = {
    home: userHome,
  };
  if (process.env.CLI_HOME) {
    cliConfig["cliHome"] = path.join(userHome, process.env.CLI_HOME);
  } else {
    cliConfig["cliHome"] = path.join(userHome, constant.DEFAULT_CLI_HOME);
  }
  process.env.CLI_HOME = cliConfig.cliHome;
  return cliConfig;
}

// function checkArgs(args) {
//   if (args.debug) {
//     process.env.LOG_LEVEL = "verbose";
//   } else {
//     process.env.LOG_LEVEL = "info";
//   }
//   //动态修改log.level 就能打印出log.verbose
//   log.level = process.env.LOG_LEVEL;
// }

function checkUserHome() {
  //user-home 包
  // console.log(userHome);
  if (!userHome || !pathExits(userHome)) {
    throw new Error(colors.red("当前登陆用户主目录不存在"));
  }
}

//检查是否是root用户 root-check
function checkRoot() {
  const rootCheck = require("root-check"); //process.seteuid/setegid 核心操作
  rootCheck();
}

function checkPkgVersion() {
  log.notice("version:", pkg.version);
}
